import { api } from '@/utils/api'

// 用户信息接口
interface UserInfo {
  isLoggedIn: boolean
  username: string
  nickname: string
  avatar: string
}

// 登录请求接口
interface LoginRequest {
  username: string
  password: string
}

// 注册请求接口
interface RegisterRequest {
  username: string
  password: string
}

// 登录响应接口
interface LoginResponse {
  token: string
  user: {
    id: number
    username: string
  }
}

// 用户信息响应接口
interface UserResponse {
  id: number
  username: string
}

/**
 * 认证服务类
 */
export class AuthService {
  /**
   * 用户登录
   */
  static async login(credentials: LoginRequest): Promise<LoginResponse> {
    try {
      const response = await api.post<LoginResponse>('/api/auth/login', credentials)
      
      if (response.success && response.data) {
        // 保存token到localStorage
        localStorage.setItem('authToken', response.data.token)
        
        // 保存用户信息
        const userInfo: UserInfo = {
          isLoggedIn: true,
          username: response.data.user.username,
          nickname: response.data.user.username,
          avatar: response.data.user.username.charAt(0).toUpperCase()
        }
        localStorage.setItem('userInfo', JSON.stringify(userInfo))
        
        return response.data
      } else {
        throw new Error(response.message || '登录失败')
      }
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    }
  }

  /**
   * 用户注册
   */
  static async register(userData: RegisterRequest): Promise<UserResponse> {
    try {
      const response = await api.post<UserResponse>('/api/auth/register', userData)
      
      if (response.success && response.data) {
        return response.data
      } else {
        throw new Error(response.message || '注册失败')
      }
    } catch (error) {
      console.error('注册失败:', error)
      throw error
    }
  }

  /**
   * 获取用户信息
   */
  static async getUserProfile(): Promise<UserResponse> {
    try {
      const response = await api.get<UserResponse>('/api/auth/profile')
      
      if (response.success && response.data) {
        return response.data
      } else {
        throw new Error(response.message || '获取用户信息失败')
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      throw error
    }
  }

  /**
   * 用户登出
   */
  static logout(): void {
    // 清除本地存储的认证信息
    localStorage.removeItem('authToken')
    localStorage.removeItem('userInfo')
  }

  /**
   * 检查用户是否已登录
   */
  static isLoggedIn(): boolean {
    const token = localStorage.getItem('authToken')
    const userInfo = localStorage.getItem('userInfo')
    
    if (!token || !userInfo) {
      return false
    }
    
    try {
      const parsedUserInfo = JSON.parse(userInfo)
      return parsedUserInfo.isLoggedIn === true
    } catch {
      return false
    }
  }

  /**
   * 获取当前用户信息
   */
  static getCurrentUser(): UserInfo | null {
    const userInfo = localStorage.getItem('userInfo')
    
    if (!userInfo) {
      return null
    }
    
    try {
      return JSON.parse(userInfo)
    } catch {
      return null
    }
  }

  /**
   * 获取认证token
   */
  static getToken(): string | null {
    return localStorage.getItem('authToken')
  }
}

// 导出类型
export type { UserInfo, LoginRequest, RegisterRequest, LoginResponse, UserResponse } 